package com.module.aichat.ui.widget.inputview

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.FrameLayout
import android.widget.TextView
import androidx.annotation.AttrRes
import androidx.appcompat.app.AppCompatActivity
import com.common.base.app.extras.setOnClickListener
import com.common.base.utils.AppUtils
import com.common.base.utils.SoftInputUtils
import com.common.base.utils.ViewUtils.getColor
import com.module.aichat.R
import com.module.aichat.data.bean.ChatUser
import com.module.aichat.data.bean.InputModel
import com.module.aichat.databinding.AichatInputViewBinding

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/06/25
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class ChatInputView(
    context: Context,
    attrs: AttributeSet?,
    @AttrRes defStyleAttr: Int
) : FrameLayout(context, attrs, defStyleAttr), EmotionKeyboard.Listener {

    constructor(
        context: Context,
        attrs: AttributeSet
    ) : this(context, attrs, 0)

    constructor(context: Context) : this(context, null, 0)

    private val mViewBinding = AichatInputViewBinding.inflate(LayoutInflater.from(context), this, true)

    var currentModel = InputModel.MODEL_NONE;//默认键盘模式
    var emotionKeyboard: EmotionKeyboard
    private var isEnableMore = false //更多模块是否能用

    private val mAdapter by lazy { AiSbListAdapter() }

    var chatInputListener: ChatInputListener? = null

    init {
        val typedArray = context.resources.obtainAttributes(attrs, R.styleable.AiChatInputView)

        val maxLength = typedArray.getInt(R.styleable.AiChatInputView_aichat_edt_max_length, 500)
        val btnSendTextColor =
            typedArray.getColor(R.styleable.AiChatInputView_aichat_btn_send_text_color, Color.WHITE)
        val btnSendBg = typedArray.getResourceId(
            R.styleable.AiChatInputView_aichat_btn_send_bg, R.drawable.bg_round_2a7fd8_100
        )
        val edtTextColor = typedArray.getColor(
            R.styleable.AiChatInputView_aichat_edt_text_color, AppUtils.getColor(R.color.aichat_gray_44)
        )

        typedArray.recycle()
//        mViewBinding.root.layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        mViewBinding.edtText.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_SEND
                || actionId == EditorInfo.IME_ACTION_DONE
                || (event != null && KeyEvent.KEYCODE_ENTER == event.keyCode && KeyEvent.ACTION_DOWN == event.action)
            ) {
                mViewBinding.edtText.append("\n")
                true
            } else {
                false
            }
        }
        AtMemberManager.init(mViewBinding.edtText)
//        mViewBinding.txtSend.isEnabled = false
        mViewBinding.txtSend.setOnClickListener(onClick = {
            sendText()
        })
        mViewBinding.edtText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                changeSendAndMore()
            }

            override fun beforeTextChanged(
                s: CharSequence?,
                start: Int,
                count: Int,
                after: Int
            ) {

            }

            override fun onTextChanged(
                s: CharSequence?,
                start: Int,
                before: Int,
                count: Int
            ) {
            }
        })
        mViewBinding.edtText.filters = arrayOf(InputFilter { source, start, end, dest, dstart, dend ->
            if ("@" == source) {
                chatInputListener?.toAtMember()
            }
            null
        })
        emotionKeyboard = EmotionKeyboard.with(context as Activity)
//            .bindEmotionView(fLayoutEmoji)
            .bindToEditText(mViewBinding.edtText)
            .bindListener(this)
            .build()

        //拦截返回键
        mViewBinding.edtText.setOnKeyListener { v, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_BACK
                && event.action == KeyEvent.ACTION_UP
            ) {
                return@setOnKeyListener (emotionKeyboard.interceptBackPress()
                        || currentModel == InputModel.MODEL_KEYBOARD).apply {
                    switchModel(InputModel.MODEL_NONE)
                }
            }
            return@setOnKeyListener false
        }

        mViewBinding.sbHrv.adapter = mAdapter

        this.setBackgroundColor(getColor(R.color.transparent))
    }

    /**
     * 变化发送和更多按钮状态
     */
    private fun changeSendAndMore() {
        if (isEnableMore) {
            if (mViewBinding.edtText.text?.isEmpty() != false) {
                mViewBinding.txtSend.visibility = View.GONE
            } else {
                mViewBinding.txtSend.visibility = View.VISIBLE
            }
        }
//        mViewBinding.txtSend.isEnabled = mViewBinding.edtText.text?.isEmpty() == false
    }


    //设置输入键盘上面的布局  键盘和表情布局切换时锁定 内容布局防止跳动
    fun setContentView(contentView: View) {
        emotionKeyboard.bindToContent(contentView)
    }

    //发送文字
    private fun sendText() {
        mViewBinding.edtText.text?.toString()
            ?.let { s ->
                chatInputListener?.sendText(s,mViewBinding.edtText.text.getSpans(0, mViewBinding.edtText.length(), ChatUser::class.java).map { it.id })
                mViewBinding.edtText.setText("")
                SoftInputUtils.setSoftInput(mViewBinding.edtText, false)
            }
    }

    override fun setEnabled(enabled: Boolean) {
        if (!enabled) {
            switchModel(InputModel.MODEL_NONE)
            mViewBinding.edtText.isCursorVisible = false
        }
        super.setEnabled(enabled)
    }

    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (!isEnabled) return false
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 切换模式
     */
    internal fun switchModel(model: InputModel) {
        if (currentModel == model) return

        val transaction = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
        currentModel = model
        mViewBinding.edtText.isCursorVisible = true
        when (currentModel) {
            InputModel.MODEL_KEYBOARD -> {//展示键盘模式
                changeSendAndMore()
                emotionKeyboard.showKeyBoard()
                chatInputListener?.onChangeModel(currentModel)
            }
            InputModel.MODEL_NONE -> {//隐藏键盘模式
                emotionKeyboard.hideSoftInput()
                emotionKeyboard.onlyHideEmotion()
                chatInputListener?.onChangeModel(currentModel)
            }

            else -> {}
        }
        transaction.commitAllowingStateLoss()
    }

    //显示键盘
    override fun showKeyBoard() {
        switchModel(InputModel.MODEL_KEYBOARD)
    }

    //隐藏键盘
    override fun hideKeyBoard() {
        switchModel(InputModel.MODEL_NONE)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        emotionKeyboard.removeListener()
    }

    fun getSendView(): TextView {
        return mViewBinding.txtSend
    }

    fun getAiSbListAdapter(): AiSbListAdapter {
        return mAdapter
    }

    fun setAiSbListAdapterData(mList:List<String>?) {
        mViewBinding.aiSbListTotal.visibility = if(!mList.isNullOrEmpty()) VISIBLE else GONE
        mAdapter.setList(mList?.chunked(2)?.firstOrNull() ?: emptyList())
    }

    fun setInitInput(mStr:String){
        mViewBinding.edtText.setText(mStr)
    }
}